package com.fivestar.pmanager.web.auth;

import static com.fivestar.pmanager.core.util.LoggerHelper.logError;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.authentication.dao.SaltSource;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.Assert;

import com.fivestar.pmanager.constants.CommonConstants;
import com.fivestar.pmanager.model.FsUserBean;
import com.fivestar.pmanager.model.SysLoginLogBean;
import com.fivestar.pmanager.service.SysLoginLogService;
import com.fivestar.pmanager.system.domain.CommonParameterBean;


/**
 * 自定义登录验证
 *
 */
public class LoginAuthenticationProvider extends
        AbstractUserDetailsAuthenticationProvider implements CommonConstants
{

    private final Logger logger = LoggerFactory.getLogger(LoginAuthenticationProvider.class);

    private PasswordEncoder passwordEncoder = new PlaintextPasswordEncoder();

    private SaltSource saltSource;

    private UserDetailsService userDetailsService;

    private SysLoginLogService sysLoginLogService;

    // ~ Methods
    // ========================================================================================================

    protected void additionalAuthenticationChecks(UserDetails userDetails,
            UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException
    {
        HttpServletRequest request = ((MyUsernamePasswordAuthenticationToken)authentication).getRequest();

        Object salt = null;

        if (this.saltSource != null)
        {
            salt = this.saltSource.getSalt(userDetails);
        }

        if (authentication.getCredentials() == null)
        {
            logger.debug("Authentication failed: no credentials provided");

            throw new BadCredentialsException("Bad credentials:" + userDetails);
        }

        String presentedPassword = authentication.getCredentials().toString();

        if (!passwordEncoder.isPasswordValid(userDetails.getPassword().toLowerCase(), presentedPassword, salt))
        {
            logger.debug("Authentication failed: password does not match stored value");

            increaseErrorTime(request.getSession());
            throw new AuthenticationServiceException("用户名或密码错误!");
        }

        request.getSession().setAttribute(SESSION_KEY_SUPPORT_USER, ((MyUserDetails)userDetails).getUser());

        //初始化公共参数
        CommonParameterBean commonParameterBean = new CommonParameterBean();
        commonParameterBean.setfsUserBean(((MyUserDetails)userDetails).getUser());
        request.getSession().setAttribute(SESSION_KEY_COMMON_PARAMTER,
                commonParameterBean);

        //记录登录日志
        try
        {
        	SysLoginLogBean sysLoginLogBean = new SysLoginLogBean();
        	sysLoginLogBean.setUserId(((MyUserDetails)userDetails).getUser().getRowId());
        	sysLoginLogBean.setLoginId(userDetails.getUsername());
        	sysLoginLogBean.setLoginTime(new Date());
        	sysLoginLogBean.setFailTimes(getErrorTime(request.getSession()));
        	sysLoginLogBean.setIp(getIpAddr(request));
        	sysLoginLogBean.setSessionId(request.getSession().getId());
            sysLoginLogService.save(sysLoginLogBean, commonParameterBean);
        }
        catch (Exception e)
        {
            logError(logger, e);
        }

        clearErrorTime(request.getSession());
    }

    protected void doAfterPropertiesSet() throws Exception
    {
        Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
    }

    protected PasswordEncoder getPasswordEncoder()
    {
        return passwordEncoder;
    }

    protected SaltSource getSaltSource()
    {
        return saltSource;
    }

    protected UserDetailsService getUserDetailsService()
    {
        return userDetailsService;
    }

    protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication)
            throws AuthenticationException
    {
        UserDetails loadedUser;
        HttpServletRequest request = ((MyUsernamePasswordAuthenticationToken)authentication).getRequest();
        try
        {
            String password = (String) authentication.getCredentials();
            loadedUser = getUserDetailsService().loadUserByUsername(username);
        }
        catch (UsernameNotFoundException notFound)
        {
            increaseErrorTime(request.getSession());
            throw new AuthenticationServiceException("用户名不存在!");
        }
        catch (Exception repositoryProblem)
        {
            throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
        }

        if (loadedUser == null)
        {
            increaseErrorTime(request.getSession());
            throw new AuthenticationServiceException("用户名不存在!");
        }
        else
        {
            FsUserBean userBean = ((MyUserDetails)loadedUser).getUser();
            //校验用户状态
            if(userBean.getStatus().equals(USER_STATE_1))
            {
                increaseErrorTime(request.getSession());
                throw new AuthenticationServiceException("用户被禁用，请联系系统管理员!");
            }

        }
        return loadedUser;
    }


    public void setPasswordEncoder(Object passwordEncoder)
    {
        Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");

        if (passwordEncoder instanceof PasswordEncoder)
        {
            this.passwordEncoder = (PasswordEncoder) passwordEncoder;
            return;
        }

        if (passwordEncoder instanceof org.springframework.security.crypto.password.PasswordEncoder)
        {
            final org.springframework.security.crypto.password.PasswordEncoder delegate = (org.springframework.security.crypto.password.PasswordEncoder) passwordEncoder;
            this.passwordEncoder = new PasswordEncoder()
            {
                private void checkSalt(Object salt)
                {
                    Assert.isNull(salt, "Salt value must be null when used with crypto module PasswordEncoder");
                }

                public String encodePassword(String rawPass, Object salt)
                {
                    checkSalt(salt);
                    return delegate.encode(rawPass);
                }

                public boolean isPasswordValid(String encPass, String rawPass, Object salt)
                {
                    checkSalt(salt);
                    return delegate.matches(rawPass, encPass);
                }
            };

            return;
        }

        throw new IllegalArgumentException("passwordEncoder must be a PasswordEncoder instance");
    }

    public void setSaltSource(SaltSource saltSource)
    {
        this.saltSource = saltSource;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService)
    {
        this.userDetailsService = userDetailsService;
    }

    private void increaseErrorTime(HttpSession session)
    {
        Integer errorTime = (Integer) session.getAttribute("errorTime");
        if(errorTime == null) errorTime = 0;
        errorTime++;
        session.setAttribute("errorTime", errorTime);
    }
    
    
    public String getIpAddr(HttpServletRequest request) { 
        String ip = request.getHeader("x-forwarded-for"); 
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
            ip = request.getHeader("Proxy-Client-IP"); 
        } 
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
            ip = request.getHeader("WL-Proxy-Client-IP"); 
        } 
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
            ip = request.getRemoteAddr(); 
        } 
        return ip; 
    } 

    private void clearErrorTime(HttpSession session)
    {
        session.setAttribute("errorTime", 0);
    }


    private int getErrorTime(HttpSession session)
    {
        Integer errorTime = (Integer) session.getAttribute("errorTime");
        if(errorTime == null) errorTime = 0;
        return errorTime;
    }

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	public void setSysLoginLogService(SysLoginLogService sysLoginLogService) {
		this.sysLoginLogService = sysLoginLogService;
	}

}
